package ThreadPool.jike.demo05;

import java.util.ArrayList;
import java.util.List;

/**
 * @param
 * @author oyz
 * @version 1.1.0
 * @description: 一次性申请所有资源避免死锁
 * @date 2022-9-15 17:48
 */
public class Allocator {

    private List<Object> list = new ArrayList<>();
    // 一次性申请所有资源
    synchronized boolean apply(Object from,Object to){
        if(list.contains(from) || list.contains(to)){
            return false;
        }else{
            list.add(from);
            list.add(to);
        }
        return true;
    }

    // 释放所有资源
    synchronized void free(Object from,Object to){
        list.remove(from);
        list.remove(to);
    }

    /**
     * synchronized如果申请资源申请不到的话，他会阻塞当前线程。后续会有juc出现来解决这个问题
     */
    class Account{
        // allocator一定要保证他是单例对象
        private Allocator allocator;
        // 余额
        private int balance;
        void transfer(Account target,int money ){
            // 缺点比较消耗性能
            while(!allocator.apply(this,target)) {
                // 锁定传出账户
                try {
                    synchronized (this){
                        // 锁定转入账户
                        synchronized (target){
                            if(this.balance>money){
                                this.balance -= money;
                                target.balance += money;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    allocator.free(this,target);
                }
            }
        }

    }






}
